import 'dart:io';
import 'package:flutter/material.dart';
import '../models/document.dart';
import '../models/document_detail.dart';
import '../models/namespace.dart';
import '../services/api_service.dart';
import '../services/auth_service.dart';
import '../widgets/document_list.dart';
import '../widgets/document_detail.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final ApiService _apiService = ApiService();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  List<Document> _documents = [];
  List<Namespace> _namespaces = [];
  DocumentDetail? _selectedDetail;
  String? _selectedDocId;
  String? _selectedNamespaceId;

  bool _isLoadingList = false;
  bool _isLoadingDetail = false;
  bool _isLoadingNamespaces = false;
  String? _error;

  // 编辑/预览状态
  bool _isPreviewMode = true;
  bool _isSaving = false;
  final TextEditingController _contentController = TextEditingController();
  final TextEditingController _nameController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _initializeApp();
  }

  @override
  void dispose() {
    _contentController.dispose();
    _nameController.dispose();
    super.dispose();
  }

  /// 初始化应用：先尝试恢复上次的文档，再加载空间列表和文档列表
  Future<void> _initializeApp() async {
    // 1. 尝试获取上次打开的文档ID
    final lastDocId = await AuthService.getLastDocumentId();

    String? targetNamespaceId;

    // 2. 如果有上次的文档ID，先获取文档详情以获得namespaceId
    if (lastDocId != null) {
      try {
        setState(() {
          _isLoadingDetail = true;
        });

        final detail = await _apiService.getDocumentDetail(lastDocId);
        targetNamespaceId = detail.namespaceId;

        // 保存文档详情，稍后显示
        setState(() {
          _selectedDetail = detail;
          _selectedDocId = lastDocId;
          _isLoadingDetail = false;
        });
      } catch (e) {
        // 文档可能已被删除，忽略错误
        setState(() {
          _isLoadingDetail = false;
        });
      }
    }

    // 3. 加载空间列表
    await _loadNamespaces();

    // 4. 确定要加载的空间ID（优先使用文档的namespaceId，其次使用第一个空间）
    if (targetNamespaceId != null && _namespaces.any((ns) => ns.id == targetNamespaceId)) {
      _selectedNamespaceId = targetNamespaceId;
    } else if (_selectedNamespaceId == null && _namespaces.isNotEmpty) {
      _selectedNamespaceId = _namespaces.first.id;
    }

    // 5. 加载文档列表
    if (_selectedNamespaceId != null) {
      await _loadDocuments(restoreDocId: lastDocId);
    }
  }

  Future<void> _loadNamespaces() async {
    setState(() {
      _isLoadingNamespaces = true;
    });

    try {
      final namespaces = await _apiService.getNamespaceList();
      setState(() {
        _namespaces = namespaces;
        _isLoadingNamespaces = false;
        // 默认选择第一个空间
        if (namespaces.isNotEmpty && _selectedNamespaceId == null) {
          _selectedNamespaceId = namespaces.first.id;
        }
      });
    } catch (e) {
      setState(() {
        _isLoadingNamespaces = false;
      });
    }
  }

  Future<void> _loadDocuments({String? restoreDocId}) async {
    setState(() {
      _isLoadingList = true;
      _error = null;
    });

    try {
      final documents = await _apiService.getDocumentList(
        namespaceId: _selectedNamespaceId,
      );
      setState(() {
        _documents = documents;
        _isLoadingList = false;
      });

      // 如果有要恢复的文档ID，且已经加载了该文档详情，则不需要再次加载
      if (restoreDocId != null && _selectedDocId == restoreDocId && _selectedDetail != null) {
        return;
      }

      // 加载第一个文档
      if (documents.isNotEmpty) {
        final firstDoc = _getFirstDocument(documents);
        if (firstDoc != null) {
          _loadDocumentDetail(firstDoc.id);
        }
      }
    } catch (e) {
      setState(() {
        _error = e.toString();
        _isLoadingList = false;
      });
    }
  }

  // 获取第一个文档（递归查找，处理嵌套情况）
  Document? _getFirstDocument(List<Document> documents) {
    if (documents.isEmpty) return null;
    final firstDoc = documents.first;
    // 如果第一个文档有子文档，返回第一个子文档，否则返回自己
    if (firstDoc.children.isNotEmpty) {
      return _getFirstDocument(firstDoc.children);
    }
    return firstDoc;
  }

  Future<void> _loadDocumentDetail(String id) async {
    // 非macOS平台，先关闭侧边栏，提升交互体验
    if (!Platform.isMacOS && _scaffoldKey.currentState?.isDrawerOpen == true) {
      Navigator.pop(context);
    }

    setState(() {
      _isLoadingDetail = true;
      _selectedDocId = id;
      _error = null;
      _isPreviewMode = true; // 切换文档时重置为预览模式
    });

    try {
      final detail = await _apiService.getDocumentDetail(id);
      if (!mounted) return;

      setState(() {
        _selectedDetail = detail;
        _isLoadingDetail = false;
        // 更新编辑器内容
        _contentController.text = detail.content;
        _nameController.text = detail.name;
      });

      // 保存上次打开的文档ID（全局）
      await AuthService.saveLastDocumentId(id);
    } catch (e) {
      setState(() {
        _error = e.toString();
        _isLoadingDetail = false;
      });
    }
  }

  Future<void> _deleteCurrentDocument() async {
    if (_selectedDocId == null) return;

    try {
      await _apiService.deleteDocument(_selectedDocId!);
      if (!mounted) return;

      // 显示成功提示
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('文档删除成功'),
          backgroundColor: Colors.green,
        ),
      );

      // 清空当前选中的详情
      setState(() {
        _selectedDetail = null;
        _selectedDocId = null;
      });

      // 刷新文档列表
      await _loadDocuments();
    } catch (e) {
      if (!mounted) return;

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('删除失败: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  void _showDeleteConfirmation() {
    if (_selectedDetail == null) return;

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除文档"${_selectedDetail!.name}"吗？此操作不可恢复。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              _deleteCurrentDocument();
            },
            style: TextButton.styleFrom(
              foregroundColor: Colors.red,
            ),
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  Widget _buildDocumentListPanel() {
    return Container(
      decoration: BoxDecoration(
        border: Border(
          right: BorderSide(
            color: Colors.grey.shade300,
            width: 1,
          ),
        ),
      ),
      child: Column(
        children: [
          // 空间下拉选择器
          Container(
            padding: const EdgeInsets.fromLTRB(16.0, 24.0, 16.0, 8.0),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: Colors.grey.shade300,
                  width: 1,
                ),
              ),
            ),
            child: _isLoadingNamespaces
                ? const Center(
                    child: SizedBox(
                      height: 20,
                      width: 20,
                      child: CircularProgressIndicator(strokeWidth: 2),
                    ),
                  )
                : DropdownButtonHideUnderline(
                    child: DropdownButton<String>(
                      isExpanded: true,
                      value: _selectedNamespaceId,
                      hint: const Text('选择空间'),
                      items: _namespaces
                          .map((namespace) => DropdownMenuItem<String>(
                                value: namespace.id,
                                child: Row(
                                  children: [
                                    Expanded(child: Text(namespace.name)),
                                    if (namespace.isPrivate)
                                      Container(
                                        margin: const EdgeInsets.only(left: 8),
                                        padding: const EdgeInsets.symmetric(
                                          horizontal: 6,
                                          vertical: 2,
                                        ),
                                        decoration: BoxDecoration(
                                          color: Colors.orange.shade100,
                                          borderRadius: BorderRadius.circular(4),
                                          border: Border.all(
                                            color: Colors.orange.shade300,
                                            width: 1,
                                          ),
                                        ),
                                        child: Text(
                                          '私',
                                          style: TextStyle(
                                            fontSize: 12,
                                            color: Colors.orange.shade700,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                      ),
                                  ],
                                ),
                              ))
                          .toList(),
                      onChanged: (String? newValue) {
                        if (newValue != null) {
                          setState(() {
                            _selectedNamespaceId = newValue;
                          });
                          _loadDocuments();
                        }
                      },
                    ),
                  ),
          ),
          Expanded(
            child: DocumentList(
              documents: _documents,
              selectedDocId: _selectedDocId,
              onDocumentSelected: _loadDocumentDetail,
              isLoading: _isLoadingList,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDetailPanel() {
    return DocumentDetailView(
      detail: _selectedDetail,
      isLoading: _isLoadingDetail,
      error: _error,
      isPreviewMode: _isPreviewMode,
      onTogglePreviewMode: _togglePreviewMode,
      contentController: _contentController,
      nameController: _nameController,
    );
  }

  void _togglePreviewMode() {
    setState(() {
      _isPreviewMode = !_isPreviewMode;
    });
  }

  Future<void> _handleSave() async {
    if (_selectedDetail == null) return;

    setState(() {
      _isSaving = true;
    });

    try {
      await _apiService.updateDocument(
        _selectedDetail!.id,
        _nameController.text,
        _contentController.text,
      );

      if (!mounted) return;

      // 更新本地数据
      setState(() {
        _selectedDetail = DocumentDetail(
          id: _selectedDetail!.id,
          name: _nameController.text,
          content: _contentController.text,
          namespaceId: _selectedDetail!.namespaceId,
        );
        _isPreviewMode = true;
        _isSaving = false;
      });

      // 刷新文档列表（名称可能变了）
      _loadDocuments(restoreDocId: _selectedDocId);

      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('保存成功'),
          backgroundColor: Colors.green,
        ),
      );
    } catch (e) {
      if (!mounted) return;

      setState(() {
        _isSaving = false;
      });

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('保存失败: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  Future<void> _handleCreate() async {
    if (_selectedNamespaceId == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('请先选择空间'),
          backgroundColor: Colors.orange,
        ),
      );
      return;
    }

    // TODO: 实现新增文档弹窗或页面
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('新增文档功能待实现'),
        backgroundColor: Colors.blue,
      ),
    );
  }

  Widget _buildMoreMenu() {
    return PopupMenuButton<String>(
      icon: const Icon(Icons.more_vert),
      enabled: _selectedDetail != null,
      onSelected: (String value) {
        switch (value) {
          case 'delete':
            _showDeleteConfirmation();
            break;
        }
      },
      itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
        const PopupMenuItem<String>(
          value: 'delete',
          child: Row(
            children: [
              Icon(Icons.delete),
              SizedBox(width: 8),
              Text('删除'),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildMacOSDetailPanel() {
    return Column(
      children: [
        // 顶部标题栏区域
        SizedBox(
          height: 52,
          child: Row(
            children: [
              // 左侧占位，为红绿灯按钮留空间
              const SizedBox(width: 70),
              // 中间标题居中
              Expanded(
                child: Center(
                  child: Text(
                    _selectedDetail?.name ?? '懒熊文档',
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                    ),
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ),
              // 右侧操作按钮
              if (_selectedDetail != null) ...[
                // 编辑/预览切换按钮
                IconButton(
                  icon: Icon(
                    _isPreviewMode ? Icons.edit_outlined : Icons.visibility_outlined,
                    size: 20,
                  ),
                  onPressed: _togglePreviewMode,
                  tooltip: _isPreviewMode ? '编辑' : '预览',
                ),
                // 保存按钮（编辑模式下显示）
                if (!_isPreviewMode)
                  IconButton(
                    icon: _isSaving
                        ? const SizedBox(
                            width: 18,
                            height: 18,
                            child: CircularProgressIndicator(strokeWidth: 2),
                          )
                        : const Icon(Icons.save_outlined, size: 20),
                    onPressed: _isSaving ? null : _handleSave,
                    tooltip: '保存',
                  ),
              ],
              IconButton(
                icon: const Icon(Icons.add, size: 20),
                onPressed: _handleCreate,
                tooltip: '新增文档',
              ),
              _buildMoreMenu(),
              const SizedBox(width: 8),
            ],
          ),
        ),
        // 文档内容区域
        Expanded(
          child: _buildDetailPanel(),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    // macOS平台：使用左右分栏布局，无AppBar
    if (Platform.isMacOS) {
      return Scaffold(
        body: Row(
          children: [
            SizedBox(
              width: 300,
              child: _buildDocumentListPanel(),
            ),
            Expanded(
              child: _buildMacOSDetailPanel(),
            ),
          ],
        ),
      );
    }

    // 其他平台：使用侧边栏
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text(_selectedDetail?.name ?? '文档管理'),
        surfaceTintColor: Colors.transparent,
        leading: IconButton(
          icon: const Icon(Icons.menu),
          onPressed: () {
            _scaffoldKey.currentState?.openDrawer();
          },
        ),
        actions: [
          if (_selectedDetail != null) ...[
            // 编辑/预览切换按钮
            IconButton(
              icon: Icon(
                _isPreviewMode ? Icons.edit_outlined : Icons.visibility_outlined,
              ),
              onPressed: _togglePreviewMode,
              tooltip: _isPreviewMode ? '编辑' : '预览',
            ),
            // 保存按钮（编辑模式下显示）
            if (!_isPreviewMode)
              IconButton(
                icon: _isSaving
                    ? const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      )
                    : const Icon(Icons.save_outlined),
                onPressed: _isSaving ? null : _handleSave,
                tooltip: '保存',
              ),
          ],
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: _handleCreate,
            tooltip: '新增文档',
          ),
          _buildMoreMenu(),
        ],
      ),
      drawer: Drawer(
        child: _buildDocumentListPanel(),
      ),
      body: _buildDetailPanel(),
    );
  }
}
